package com.badger.spring.cloud.alibaba.consumer.config;

import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.netflix.hystrix.exception.HystrixRuntimeException;

import feign.FeignException;
import feign.FeignException.FeignServerException;
import lombok.extern.slf4j.Slf4j;

/**
 * 全局异常捕获
 * @author liqi
 */
@Slf4j
@ControllerAdvice
public class WholeExceptionHandler {

    /**
     * 默认最大的异常
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Map<String, String> defaultException(HttpServletRequest req, Exception e) {
        log.error(e.getMessage());
        e.printStackTrace();
        Map<String, String> dataMap = new HashMap<>();
        dataMap.put("500", "系统异常:" + e.getMessage());
        return dataMap;
    }

    /**
     * openfeign 远程调用服务异常
     * 主要表现为：服务端返回系统级别异常500 401 等，连接超时等
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = { FeignServerException.class, HystrixRuntimeException.class })
    @ResponseBody
    public Map<String, String> feignServerException(HttpServletRequest req, FeignServerException e) {
        log.error(e.getMessage());
        e.printStackTrace();
        Charset charset = Charset.forName("utf-8");
        Map<String, String> dataMap = new HashMap<>();
        dataMap.put("501", charset.decode(e.responseBody().get()).toString());
        return dataMap;
    }

    /**
     * openfeign 全局大异常
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = { FeignException.class })
    @ResponseBody
    public Map<String, String> feignException(HttpServletRequest req, FeignException e) {
        log.error(e.getMessage());
        e.printStackTrace();
        Map<String, String> dataMap = new HashMap<>();
        dataMap.put("501", e.getMessage());
        return dataMap;
    }
}
